CSS in JS
JavaScriptを用いてCSSを生成する
初出: 2014-11
2014-11にNationJSで行われた講演
by Christopher Chedeau
実装するときのイメージ
JavaScriptのオブジェクトとして、スタイルを定義する
定義したオブジェクトを、class属性で参照する
code:jsx
const styles = {
container: {
background-color: 'gray',
}
};
const Component = () => {
return <div className={styles.container}></div>
};
スタイルではなく、「スタイル情報を含むコンポーネント」を定義するのがstyled-component
code:js
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles({
root: {
backgroundColor: 'red',
color: props => props.color,
},
});
export default function MyComponent(props) {
const classes = useStyles(props);
return <div className={classes.root} />;
}
styled-componentsの例
code:jsx
import React from 'react';
import styled from 'styled-components';
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
Aphroditeの例
code:js
import React, { Component } from 'react';
import { StyleSheet, css } from 'aphrodite';
class App extends Component {
render() {
return <div>
<span className={css(styles.red)}>
This is red.
</span>
<span className={css(styles.hover)}>
This turns red on hover.
</span>
<span className={css(styles.small)}>
This turns red when the browser is less than 600px width.
</span>
<span className={css(styles.red, styles.blue)}>
This is blue.
</span>
<span className={css(styles.blue, styles.small)}>
This is blue and turns red when the browser is less than
600px width.
</span>
</div>;
}
}
const styles = StyleSheet.create({
red: {
backgroundColor: 'red'
},
blue: {
backgroundColor: 'blue'
},
hover: {
':hover': {
backgroundColor: 'red'
}
},
small: {
'@media (max-width: 600px)': {
backgroundColor: 'red',
}
}
});
ref
ライブラリが比較されてる